﻿//bibaoke.com

using System.Linq;
using System.Collections.Generic;
using Less.Text;
using System.Windows.Forms;

namespace Less.WebBrowserQuery
{
    internal class FilterByTagName : ElementFilter
    {
        internal string Name
        {
            get;
            private set;
        }

        internal FilterByTagName(string name)
        {
            this.Name = name;
        }

        protected override IEnumerable<HtmlElement> EvalThis(HtmlDocument document)
        {
            return document.GetElementsByTagName(this.Name).Cast<HtmlElement>();
        }

        protected override IEnumerable<HtmlElement> EvalThis(HtmlDocument document, IEnumerable<HtmlElement> source)
        {
            if (document.IsNotNull())
            {
                HtmlElement[] elements = document.GetElementsByTagName(this.Name).Cast<HtmlElement>().ToArray();

                return source.SelectMany(i => elements.Where(j => i == j || i.All.Cast<HtmlElement>().Contains(j)));
            }
            else
            {
                return source.SelectMany(i => i.All.Cast<HtmlElement>().Where(
                    j =>
                    j.TagName.CompareIgnoreCase(this.Name)));
            }
        }
    }
}
